<?php


class jwt
{
    protected static $key = "344";

    public static function encode($data): string
    {
        $time = time();                 //当前时间
            $token = [
            'iss'   => '',              //签发者 可选
            'iat'   => $time,           //签发时间
            'exp'   => $time+7200,      //过期时间,这里设置2个小时
            'data'  => $data,
        ];
        return  \Firebase\JWT\JWT::encode($token, self::$key); //输出Token
    }

    //解析token
    public static function decode($jwt) :array
    {
        try {
            \Firebase\JWT\JWT::$leeway = 60;//当前时间减去60，把时间留点余地
            $decoded = \Firebase\JWT\JWT::decode($jwt, self::$key, ['HS256']); //HS256方式，这里要和签发的时候对应
            $arr = (array)$decoded;
            return ['code'=>1,'data'=>$arr["data"]];
        } catch(\Firebase\JWT\SignatureInvalidException $e) {   //签名不正确
            return ['code'=>403 ,"msg"=>$e->getMessage()];
        }catch(\Firebase\JWT\BeforeValidException $e) {         // 签名在某个时间点之后才能用
            return ['code'=>403 ,"msg"=>$e->getMessage()];
        }catch(\Firebase\JWT\ExpiredException $e) {             // token过期
            return ['code'=>403 ,"msg"=>$e->getMessage()];
        }catch(Exception $e) {                                  //其他错误
            return ['code'=>403 ,"msg"=>$e->getMessage()];
        }
    }
}